package com.haibara.codesubmiteval.exception;

import com.haibara.codesubmiteval.common.BaseResponse;
import com.haibara.codesubmiteval.common.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 业务异常
    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException : {}", e.getMessage());
        return BaseResponse.error(e.getCode(), e.getMessage());
    }

    // 运行时异常
    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException :", e);
        return BaseResponse.error(ErrorCode.SYSTEM_ERROR.getCode(), "系统错误 : " + e.getMessage());
    }

    // Valid异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> validExceptionHandler(MethodArgumentNotValidException e) {
        log.error("ConstraintViolationException : {}", e.getMessage());
        String defaultMessage = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return BaseResponse.error(ErrorCode.PARAMS_ERROR.getCode(), defaultMessage);
    }

    // SQL异常
    @ExceptionHandler(DataAccessException.class)
    public BaseResponse<?> validExceptionHandler(DataAccessException e) {
        // 使用日志框架记录完整堆栈（包含异常链）
        log.error("DataAccessException: ", e);  // 注意这里用逗号分隔，不是占位符
        return BaseResponse.error(ErrorCode.PARAMS_ERROR.getCode(), "数据库操作异常");
    }


}
